//服务接入保存模板
function saveTemplate() {
	var arr = $('#tb_template').bootstrapTable('getSelections');
	if (arr.length == 0) {
		window.wxc.xcConfirm("请选择需要操作的数据！", window.wxc.xcConfirm.typeEnum.confirm,{
			title: "提示"
		});
	} else if(arr.length > 1) {
		window.wxc.xcConfirm("只能选择单条数据进行操作！", window.wxc.xcConfirm.typeEnum.confirm,{
			title: "提示"
		});
	} else if(arr.length == 1){
		var templateId = arr[0].id;
		var templateName = arr[0].templateName;
        var option = {
			title: "提示",
			btn: parseInt("0011",2),
			onOk: function(){
				var url = "/zhgl-jzstyxx-manage/serviceAccess/saveTemplate";
				var datapost = {
					"templateId" : templateId,
					"templateName" : templateName,
					"key" : key
				}
				$.post(url, datapost, function() {
					window.location = "/zhgl-jzstyxx-manage/serviceAccess/page?key=" + key;
				});
				
			}
		}
		window.wxc.xcConfirm("是否保存此模板？", "custom", option);
	}
}
//服务接入取消操作返回
function cancel() {
//	window.location = "/queueAccess/page";
	//history.go(-1);
	window.location = "/zhgl-jzstyxx-manage/serviceAccess/page?key=" + key;
}



 
$(function() {

	var oTable = new TableInit();
	oTable.Init();

	 $("#btn_query").click(function () {
		 $("#tb_template").bootstrapTable('destroy');
		 oTable.Init();
	 });
});

var TableInit = function() {
	var oTableInit = new Object();

	oTableInit.Init = function() {

		$("#tb_template").bootstrapTable({
			url : '/zhgl-jzstyxx-manage/template/getTemplate',// 请求后台参数
			method : 'post', // 请求方式（*）
			toolbar : '#toolbar', // 工具按钮用哪个容器
			dataType : 'json',
			striped : true, // 是否显示行间隔色
			cache : false, // 是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
			pagination : true, // 是否显示分页（*）
			singleSelect : false, // 单选CheckBox
			sortable : true, // 是否启用排序
			sortOrder : "asc", // 排序方式
			queryParams : oTableInit.queryParams,// 传递参数（*）
			sidePagination : "server", // 分页方式：client客户端分页，server服务端分页（*）
			pageNumber : 1, // 初始化加载第一页，默认第一页
			pageSize : 10, // 每页的记录行数（*）
			pageList : [ 10, 20, 30 ], // 可供选择的每页的行数（*）
			strictSearch : true,
			clickToSelect : true, // 是否启用点击选中行
			// height: 550, //行高，如果没有设置height属性，表格自动根据记录条数决定表格高度
			uniqueId : "id", // 每一行的唯一标识，一般为主键列
			cardView : false, // 是否显示详细视图
			rowStyle : function rowStyle(row, index) {
				return {
					css : {
						"font-size" : "14px",
						"height" : "15px",
						"line-height" : 1
					}
				};
			},
			detailView : false, // 是否显示父子表
			columns : [ {
				checkbox : true,
				width:'4%'
			}, {
				field : 'id',
				title : '序号',
				align : 'center',
				width:'8%',
				formatter : function(value, row, index) {
					var pageSize=$('#tb_template').bootstrapTable('getOptions').pageSize;//通过表的#id可以得到每页多少条
        			var pageNumber=$('#tb_template').bootstrapTable('getOptions').pageNumber;//通过表的#id可以得到当前第几页
					return pageSize*(pageNumber-1)+index+1;
				}
			},  {
				field : 'templateName',
				title : '模板名称',
				align : 'center',
				width : '20%',
				formatter : function(value, row, index) {
						return "<span title=\""+value+"\">"+value+"</span>"				
				}
			},  {
				field : 'templateContent',
				title : '模板内容',
				align : 'center',
				formatter : function(value, row, index) {
					if(value!=null){
						return "<span title=\""+value+"\">"+value+"</span>"
					}else{
						return ""}
				}
			}
			]
		});
	};
	//得到查询的参数
    oTableInit.queryParams = function (params) {
        temp = {       
        	limit: params.limit,   
            offset: params.offset,  
            templateName:  $.trim($("#templateName").val())       	
        };
        return temp;
    };

    return oTableInit;
}

//新增
function AddTemplate(){
	$("#myModalLabel").text("新增")
	$("#cId").val("");
	$("#templatename").val("");
	$("#templateContent").val("");
	$("#sampleData").val("");
	$("#templateSample").val("");
	validform().resetForm();
	$(".error").removeClass("error");
	$("#addOrEditModal").modal('show');
}
//修改页面
function editById(){
	$("#templatename").val("");
	$("#templateContent").val("");
	$("#sampleData").val("");
	$("#templateSample").val("");
	validform().resetForm();
	$(".error").removeClass("error");
	var url = "/zhgl-jzstyxx-manage/template/getById";
	var arr = $('#tb_template').bootstrapTable('getSelections');
	if(arr.length==0){
		window.wxc.xcConfirm("请选择需要操作的数据！", window.wxc.xcConfirm.typeEnum.confirm,{
			title: "提示",
			btn: parseInt("0001",2), //确定按钮
		})
	}else if(arr.length>1){
		window.wxc.xcConfirm("只能选择单条数据进行操作！", window.wxc.xcConfirm.typeEnum.confirm,{
			title: "提示",
			btn: parseInt("0001",2), //确定按钮
		});
	}else{
		$("#myModalLabel").text("修改")
		$("#addOrEditModal").modal('show');
		$.ajax({
			url:url,
			data:{"id":arr[0].id},
			type:"POST",
			dataType:"json",
			success:function(template){
				$("#cId").val(template.id);
				$("#templatename").val(template.templateName);
				$("#templateContent").val(template.templateContent);
				$("#sampleData").val(template.sampleData);
				$("#templateSample").val(template.templateSample);
			}
		})
	}
}

//保存
function saveAddOrEdit(){
	var base = new Base64();
	if (validform().form()) {
		$(':button').attr('disabled',"true");
	var cId = $("#cId").val();
	var templatename = $("#templatename").val().trim();
	var templateContent = $("#templateContent").val().trim();
	templateContent=base.encode(templateContent);
	var sampleData=$("#sampleData").val().trim();
	sampleData=base.encode(sampleData);
	var templateSampleVal = $("#templateSample").val().trim();
	var datapost = {
		"id":cId,
		"templateName":templatename,
		"templateContent":templateContent,
		"sampleData":sampleData
	}
	var url;
	if(cId!=""){
		url ="/zhgl-jzstyxx-manage/template/changeTemplate";
	}else{
		url="/zhgl-jzstyxx-manage/template/addTemplate"
	}
	if(templateContent!=""&&sampleData!=""){
			if(templateSampleVal!=""){
					$.ajax({
						url:url,
						data:datapost,
						type:"POST",
						dataType:"json",
						success:function(result){
							$(':button').removeAttr("disabled");
							if(result.state==200){
								window.wxc.xcConfirm(result.message, window.wxc.xcConfirm.typeEnum.confirm,{
									title: "提示",
									btn: parseInt("0001",2), //确定按钮
								});
							}else if(result.state==400){
								window.wxc.xcConfirm(result.message, window.wxc.xcConfirm.typeEnum.confirm,{
									title: "提示",
									btn: parseInt("0001",2), //确定按钮
								});
							}
					    	 $('#tb_template').bootstrapTable('refresh');
							 $("#addOrEditModal").modal('hide');
							}
					})
				}else{
					
					window.wxc.xcConfirm("请优先数据模板匹配后提交,确保准确！", window.wxc.xcConfirm.typeEnum.confirm,{
						title: "提示",
						btn: parseInt("0001",2), //确定按钮
						onOk:function(){
							$(':button').removeAttr("disabled");
						},
						onClose:function(){
							$(':button').removeAttr("disabled");
						}
					});
				}
			}else{
				window.wxc.xcConfirm("模板内容和数据示例必须都填", window.wxc.xcConfirm.typeEnum.confirm,{
					title: "提示",
					btn: parseInt("0001",2), //确定按钮
					onOk:function(){
						$(':button').removeAttr("disabled");
					},
					onClose:function(){
						$(':button').removeAttr("disabled");
					}
				});
			}
	}
}
//删除
function deleteByIds(){
	 var arr = $('#tb_template').bootstrapTable('getSelections');
	 var dataNum = arr.length;
	 if (arr.length == 0) {
		 window.wxc.xcConfirm("请选择你要删除的数据！", window.wxc.xcConfirm.typeEnum.confirm,{
				title: "提示",
				btn: parseInt("0001",2), //确定按钮
			});
	 } else {
		 var ids = "";
		    for(var a = 0; a<arr.length; a++) {
		    	ids+=arr[a].id+",";
		    	}
		    ids=ids.substring(0,ids.length-1);
	 var url = '/zhgl-jzstyxx-manage/template/deleteByIds';
	 window.wxc.xcConfirm("确认删除吗？", window.wxc.xcConfirm.typeEnum.confirm,{
			title: "提示",
			onOk:  function(){
					$.ajax({
                		type: 'POST',
                		url: url,
                		dataType: "json",
                		data:{'ids':ids},
                		success: function (result) {
                			if(result.state==400){
                				window.wxc.xcConfirm(result.message, window.wxc.xcConfirm.typeEnum.confirm,{
                					title: "提示",
                					btn: parseInt("0001",2), //确定按钮
                				});
                			}else if(result.state==200){
                				window.wxc.xcConfirm(result.message, window.wxc.xcConfirm.typeEnum.confirm,{
                					title: "提示",
                					btn: parseInt("0001",2), //确定按钮
                				});
                			
                				$('#tb_template').bootstrapTable('refresh');
                			}
                }
            })	
		}
	 })
	}
}
//数据模板匹配
function match(){
	var str = $("#templateContent").val().trim();
	var data=$("#sampleData").val().trim();
	var all = /^[0-9]+$/;
	try{	
		if(str!=""&&data!=""){
			if(all.test(data)){
				$("#templateSample").val("");
			}else{
				var jsonObj = JSON.parse(data);
				var arr=str.replace(/\{{\w*\}}/g,function(w){
					r=w.substr(2,w.length-4);
					return jsonObj[r]==null?w:jsonObj[r];
				})
				$("#templateSample").val(arr)
			}
			
		}else{
			$("#templateSample").val(str)
		}
	}catch(e){
		window.wxc.xcConfirm("数据格式错误！例:{\"name\":\"某\",\"age\":\"21\"}", window.wxc.xcConfirm.typeEnum.confirm,{
			title: "提示",
			btn: parseInt("0001",2), //确定按钮
		});
	}
	
}
//校验
function validform() {
    return $("#addOrEdit").validate({
        rules: {
        	templatename:{
                required:true,
                maxlength:32,
                stringCheck:true,
                remote:{
                  	   url:"/zhgl-jzstyxx-manage/template/checkName",
                       type:"post",
                       dataType:"json",
                       async:false,
                       cache:false,
                       data:{
                    	   templatename:function(){
                      		 var formData = $('#addOrEdit').serializeJSON();
                      		 return formData.templatename;
                      	 	},
                      	 	id:function(){
                         		 var formData = $('#addOrEdit').serializeJSON();
                          		 return formData.id;
                          	 	}
                       	},
              		dataFilter:function(data){
              				return data;
              		}
                   }
           },
           templateContent: {
                required: true,
                maxlength:2000,
            },
            sampleData:{
            	required: true,
            	maxlength:2000,
            	jsonStr:true,
            },
        },
		     messages: {
		    	 templatename:{
		             required:"模板名称不能为空",
		             maxlength:"最多输入32位",
		             stringCheck:jQuery.validator.addMethod("stringCheck", function(value, element) {
		            	 var all= /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
		                 return this.optional(element) || all.test(value);       
		             }, "模板名称不能有特殊字符"),
		             remote:"模板名称已存在",
		        },
		        templateContent: {
		        	required:"模板内容不能为空",
		             maxlength:"最多输入2000位",
		        },
		        sampleData:{
		        	required:"数据示例不能为空",
		        	maxlength:"最多输入2000位",
	            	jsonStr:jQuery.validator.addMethod("jsonStr", function(value) {
	            		var all= /^[0-9]+$/;
	            		try{
	            			if(value.trim()!=""){
	            				if(all.test(value.trim())){
	            					return false;
	            				}
	            				var obj=JSON.parse(value.trim())
	            			}
	            			return true ;
	            		}catch(e){
	            			return false;
	            		}
	            	},"数据格式不对,应{\"name\":\"某某\",\"age\":\"12\"}")
	          
	            }
		 },
    })
}


function Base64() {
	_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	// public method for encoding 
	this.encode = function(input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = _utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2)
					+ _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
		}
		return output;
	}

	// public method for decoding 
	this.decode = function(input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		while (i < input.length) {
			enc1 = _keyStr.indexOf(input.charAt(i++));
			enc2 = _keyStr.indexOf(input.charAt(i++));
			enc3 = _keyStr.indexOf(input.charAt(i++));
			enc4 = _keyStr.indexOf(input.charAt(i++));
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			output = output + String.fromCharCode(chr1);
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = _utf8_decode(output);
		return output;
	}

	// private method for UTF-8 encoding 
	_utf8_encode = function(string) {
		string = string.replace(/\r\n/g, "\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if ((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}
		return utftext;
	}

	// private method for UTF-8 decoding 
	_utf8_decode = function(utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while (i < utftext.length) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if ((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i + 1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = utftext.charCodeAt(i + 1);
				c3 = utftext.charCodeAt(i + 2);
				string += String.fromCharCode(((c & 15) << 12)
						| ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}

function templateContentChange(){
	$("#templateSample").val("");
}

function sampleDataChange(){
	$("#templateSample").val("");
}

